#!/bin/bash

set -o errexit
set -o xtrace

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions
cluster="some-name-rs0"


setup_cluster() {
    # create cluster
    kubectl_bin apply \
        -f $conf_dir/secrets.yml \
        -f $test_dir/conf/pumba.yml

    apply_cluster $conf_dir/$cluster.yml

    # check if all 3 Pods started
    wait_for_running $cluster 3
}

pumba_pod() {
    local action=$1
    local pod=$(get_operator_pod)

    # run chaos for Pod
    run_pumba $action "re2:$pod"
    sleep 2

    wait_pod $pod
}

pause_pod() {
    local pod=$(get_operator_pod)

    # run chaos for Pod
    kubectl_bin exec -it "$(get_pumba)" -- /pumba -l info pause --duration 1m "re2:$pod" &
    pid=$!
    sleep 10

    desc 'check if operator works fine: scale down from 4 to 3'
    kubectl_bin get psmdb -o yaml ${cluster%%-rs0} \
        | sed -e 's/size: 5/size: 3/' \
        | kubectl_bin apply -f-

    # wait for unpause
    wait $pid

    # check if Pod started
    wait_pod $pod
    sleep 10

    # check scale down
    wait_for_delete pod/$cluster-3
}

netem_pod() {
    local pod=$(get_operator_pod)

    # run chaos for Pod
    kubectl_bin exec -it "$(get_pumba)" -- /pumba -l info netem --tc-image 'gaiadocker/iproute2' --duration 1m loss --percent 100 --correlation 100 "re2:$pod" &
    pid=$!
    sleep 10

    desc 'check if operator works fine: scale up from 3 to 4'
    kubectl_bin get psmdb -o yaml ${cluster%%-rs0} \
        | sed -e 's/size: 3/size: 5/' \
        | kubectl_bin apply -f-

    # wait for unpause
    wait $pid || :

    # check if Pod started
    wait_pod $pod
    sleep 60

    # check scale up
    wait_for_running $cluster 4
}


main() {
    create_namespace $namespace
    ## TODO: kubectl_bin apply -f $test_dir/conf/quota.yml
    deploy_operator

    desc 'create PSMDB cluster'
    setup_cluster

    desc 'kill operator'
    pumba_pod kill
    desc 'check if operator works fine: scale up from 3 to 4'
    kubectl_bin get psmdb -o yaml ${cluster%%-rs0} \
        | sed -e 's/size: 3/size: 5/' \
        | kubectl_bin apply -f-
    wait_for_running $cluster 4

    desc 'rm operator'
    pumba_pod rm
    desc 'check if operator works fine: scale down from 4 to 3'
    kubectl_bin get psmdb -o yaml ${cluster%%-rs0} \
        | sed -e 's/size: 5/size: 3/' \
        | kubectl_bin apply -f-
    wait_for_delete pod/$cluster-3

    desc 'stop operator'
    pumba_pod stop
    desc 'check if operator works fine: scale up from 3 to 4'
    kubectl_bin get psmdb -o yaml ${cluster%%-rs0} \
        | sed -e 's/size: 3/size: 5/' \
        | kubectl_bin apply -f-
    wait_for_running $cluster 4

    desc 'pause operator'
    pause_pod

    desc 'emulate bad network'
    netem_pod

    destroy $namespace
}

main
